package com.shawbs.vueblog.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shawbs.vueblog.comom.PageInfo;
import com.shawbs.vueblog.comom.Result;
import com.shawbs.vueblog.entity.Blog;
import com.shawbs.vueblog.entity.User;
import com.shawbs.vueblog.mapper.UserMapper;
import com.shawbs.vueblog.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 关注公众号：MarkerHub
 * @since 2021-08-12
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public Result listPage(int pageNum, int pageSize, String keyWord) {
        //分页参数
        Page<User> page = new Page<>(pageNum,pageSize);

        //其它参数
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //模糊查询
        lambdaQueryWrapper.like(User::getUsername,keyWord);
        lambdaQueryWrapper.like(User::getEmail,keyWord);
        //排序，这里使用的是created字段降序，支持多个条件并列排序
        lambdaQueryWrapper.orderByDesc(User::getCreated);

        Page<User> pageData = (Page<User>) super.page(page,lambdaQueryWrapper);

        List<User> records = pageData.getRecords();
        List list = new ArrayList();
        for (User record : records) {
            list.add(record);
        }
        int total = super.count();

        return Result.success(new PageInfo(total, list));
    }

    @Override
    public User getById(Long id) {
        User user = super.getById((id));
        return user;
    }

    @Override
    public Result addUser(User user) {
        String password = user.getPassword();
        user.setPassword(SecureUtil.sha256(password));
        super.save(user);
        return Result.success("新增成功", null);
    }

    @Override
    public Result editUser(User user) {
        String password = user.getPassword();
        user.setPassword(SecureUtil.sha256(password));
        super.updateById(user);
        return Result.success("修改成功", null);
    }

    @Override
    public Result removeUser(Long id) {
        super.removeById(id);
        return Result.success("删除成功", null);
    }

    @Override
    public Result removeUsers(Collection ids) {
        super.removeByIds(ids);
        return Result.success("删除成功", null);
    }
}
